#include "average_lib.h"
#include <string.h>
#include <stdint.h>
#include "math.h"
#include <stdbool.h>

// 添加新数据并更新滑动平均
int updateMovingAverage(MovingAverage_handle *ma, int newValue, int *out_val)
{
    if (ma == NULL)
    {
        /*指针为空算毛直接报错*/
        return -1;
    }
    if (ma->data == NULL)
    {
        /*指针为空算毛直接报错*/
        return -2;
    }
    if (out_val == NULL)
    {
        /*指针为空算毛直接报错*/
        return -3;
    }
    // 如果窗口未满，则添加新数据
    if (ma->count < ma->window_size)
    {
        ma->data[ma->head] = newValue;
        ma->sum += newValue;
        ma->head = (ma->head + 1) % ma->window_size; // 环形缓冲区更新
        ma->count++;
    }
    else
    {
        // 窗口已满，移除最旧的数据，添加新数据
        int oldValue = ma->data[ma->head];
        ma->data[ma->head] = newValue;
        ma->sum = ma->sum - oldValue + newValue;
        ma->head = (ma->head + 1) % ma->window_size; // 环形缓冲区更新
    }
    // 计算并返回当前平均值
    *out_val = ma->sum / ma->count;
    return 0;
}

MovingAverage_handle *MovingAverage_handle_create(int window_size)
{
    /*元素小于2的情况，明显不适用滑动求平均，直接返回空*/
    if (window_size < 2)
    {
        return NULL;
    }
    MovingAverage_handle *handle = malloc(sizeof(MovingAverage_handle));
    if (handle)
    {
        memset(handle, 0x00, sizeof(MovingAverage_handle));
        handle->window_size = window_size;
        handle->data = calloc(window_size, sizeof(int));
        /*如果不能申请到需要的内存大小，那本身申请到的句柄内存也需要还回去*/
        if (handle->data == NULL)
        {
            free(handle);
            handle = NULL;
        }
    }
    return handle;
}

int MovingAverage_handle_del(MovingAverage_handle **handle)
{
    /*指针为空的情况下，没有必要释放内存*/
    if (*handle == NULL)
    {
        return -1;
    }
    if ((*handle)->data)
    {
        free((*handle)->data);
    }
    free((*handle));
    (*handle) = NULL;
    return 0;
}
